package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class LoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @SneakyThrows
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(loginCheck)")
    public Object checkLogin(ProceedingJoinPoint joinPoint,LoginCheck loginCheck){
        //获取请求对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //转换为HttpServletRequest
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        //获取token
        String token = request.getHeader("token");
        //定义redis key
        String key = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        if (loginCheck.isLogin()){
            //如果token为空，则未登录
            if (StringUtils.isEmpty(token)){
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
            //token不为空，从缓存中获取数据
            UserInfo userInfo =(UserInfo) redisTemplate.opsForValue().get(key);
            if (null == userInfo){
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
        }
        //如果不需要登录，但是有需要用户信息
        if (!StringUtils.isEmpty(token)){
            //从缓存中获取数据
            UserInfo userInfo =(UserInfo) redisTemplate.opsForValue().get(key);
            if (null != userInfo){
                //存储用户id
                AuthContextHolder.setUserId(userInfo.getId());
            }
        }
        //执行方法体
        return joinPoint.proceed();
    }
}
